//
//  RegisterViewController.m
//  EggSteward
//
//  Created by 王道林 on 16/8/29.
//  Copyright © 2016年 王道林. All rights reserved.
//

#import "RegisterViewController.h"
#import "BaseTextField.h"
#import "BaseButton.h"
#import "Masonry.h"
#import "DLWNetworkingParser.h"
#import "ZhengZe.h"
@interface RegisterViewController ()<UITextFieldDelegate>
@property (nonatomic, strong) UIImageView *imageview;
@property (nonatomic, strong) BaseTextField *textFieldPhone;
@property (nonatomic, strong) UIView *viewPhone;
@property (nonatomic, strong) BaseTextField *textfieldText;
@property (nonatomic, strong) UIView *viewText;
@property (nonatomic, strong) BaseButton *buttonGetText;
@property (nonatomic, strong) BaseTextField *textFieldPwd;
@property (nonatomic, strong) UIView *viewPwd;
@property (nonatomic, strong) BaseButton *buttonRegister;
@property (nonatomic, strong) UIAlertController *alertController;
@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setAttribute];
    [self createSubview];
    [self addGesture];
}

#pragma mark -设置透明属性
- (void)setAttribute
{
    self.navigationItem.title = @"注册";
    // 设置title 的颜色.属性
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    // bar的背景色
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.145 green:0.694 blue:0.283 alpha:1.000];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}

#pragma mark -创建控件
- (void)createSubview
{
    // 背景图片
    _imageview = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loginBack"]];
    [self.view addSubview:_imageview];
    [_imageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view);
        make.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_top);
        make.height.mas_equalTo(self.view.mas_height).multipliedBy(0.28);
    }];
    
    // 手机号的textField
    _textFieldPhone = [[BaseTextField alloc] init];
    [self.view addSubview:_textFieldPhone];
    _textFieldPhone.keyboardType = UIKeyboardTypeNumberPad;
    _textFieldPhone.borderStyle = UITextBorderStyleNone;
    _textFieldPhone.placeholder = @"请输入手机号";
    _textFieldPhone.delegate = self;
    [_textFieldPhone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_imageview.mas_bottom).with.offset(40);
        make.left.mas_equalTo(self.view.mas_left).with.offset(40);
        make.right.mas_equalTo(self.view.mas_right).with.offset(-40);
        make.height.mas_equalTo(50);
    }];
    //电话号下面的横条
    _viewPhone = [[UIView alloc] init];
    [self.view addSubview:_viewPhone];
    _viewPhone.backgroundColor = [UIColor grayColor];
    [_viewPhone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_textFieldPhone.mas_bottom).with.offset(0);
        make.left.mas_equalTo(self.view.mas_left).with.offset(40);
        make.right.mas_equalTo(self.view.mas_right).with.offset(-40);
        make.height.mas_equalTo(1);
    }];

    // 验证码
    _textfieldText = [[BaseTextField alloc] init];
    [self.view addSubview:_textfieldText];
    _textfieldText.borderStyle = UITextBorderStyleNone;
    _textfieldText.placeholder = @"请输入验证码";
    _textfieldText.keyboardType = UIKeyboardTypeNumberPad;
    _textfieldText.delegate = self;
    [_textfieldText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_textFieldPhone.mas_bottom).with.offset(40);
        make.left.mas_equalTo(self.view.mas_left).with.offset(40);
        make.width.mas_equalTo(_textFieldPhone.mas_width).multipliedBy(0.4);
        make.height.mas_equalTo(50);
    }];
    //  注册的button
    _buttonGetText = [BaseButton buttonWithType:UIButtonTypeSystem];
    [_buttonGetText setTitle:@"获取验证码" forState:UIControlStateNormal];
    _buttonGetText.titleLabel.font = [UIFont systemFontOfSize:17];
    [_buttonGetText setTintColor:[UIColor colorWithRed:0.157 green:0.651 blue:0.278 alpha:1.000]];
    [_buttonGetText addTarget:self action:@selector(getTextAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_buttonGetText];
    [_buttonGetText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_textFieldPhone.mas_bottom).with.mas_offset(40);
        make.right.mas_equalTo(_textFieldPhone.mas_right);
        make.width.mas_equalTo(_textFieldPhone.mas_width).multipliedBy(0.4);
        make.height.mas_equalTo(50);
    }];
    

    //验证码下面的横条
    _viewText = [[UIView alloc] init];
    [self.view addSubview:_viewText];
    _viewText.backgroundColor = [UIColor grayColor];
    [_viewText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_textfieldText.mas_bottom).with.offset(0);
        make.left.mas_equalTo(self.view.mas_left).with.offset(40);
        make.right.mas_equalTo(self.view.mas_right).with.offset(-40);
        make.height.mas_equalTo(1);
    }];
    // 密码
    _textFieldPwd = [[BaseTextField alloc] init];
    [self.view addSubview:_textFieldPwd];
    _textFieldPwd.borderStyle = UITextBorderStyleNone;
    _textFieldPwd.placeholder = @"请输入密码";
        _textFieldPwd.delegate = self;
    _textFieldPwd.secureTextEntry = YES;
    [_textFieldPwd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_textfieldText.mas_bottom).with.offset(40);
        make.left.mas_equalTo(self.view.mas_left).with.offset(40);
        make.right.mas_equalTo(self.view.mas_right).with.offset(-40);
        make.height.mas_equalTo(50);
    }];
    
    //密码下面的横条
    _viewPwd = [[UIView alloc] init];
    [self.view addSubview:_viewPwd];
    _viewPwd.backgroundColor = [UIColor grayColor];
    [_viewPwd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_textFieldPwd.mas_bottom).with.offset(0);
        make.left.mas_equalTo(self.view.mas_left).with.offset(40);
        make.right.mas_equalTo(self.view.mas_right).with.offset(-40);
        make.height.mas_equalTo(1);
    }];

    // 注册的button
    _buttonRegister = [BaseButton buttonWithType:UIButtonTypeCustom];
    [_buttonRegister setTitle:@"注册" forState:UIControlStateNormal];
    // 切圆角
    _buttonRegister.layer.masksToBounds = YES;
    _buttonRegister.layer.cornerRadius = 25;
    _buttonRegister.titleLabel.font = [UIFont systemFontOfSize:25];
    _buttonRegister.backgroundColor = [UIColor colorWithRed:0.157 green:0.651 blue:0.278 alpha:1.000];
    // button的点击方法
    [_buttonRegister addTarget:self action:@selector(registerAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_buttonRegister];
    [_buttonRegister mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_textFieldPwd.mas_bottom).with.mas_offset(40);
        make.left.mas_equalTo(self.view.mas_left).with.mas_offset(70);
        make.right.mas_equalTo(self.view.mas_right).with.mas_offset(-70);
        make.height.mas_equalTo(50);
    }];
    
    // 提示框
    _alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入电话号" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [_alertController dismissViewControllerAnimated:YES completion:nil];
    }];
    [_alertController addAction:actionCancel];

}


#pragma mark - 获取验证码
- (void)getTextAction:(BaseButton *)button
{
    if (![ZhengZe isMobile:_textFieldPhone.text]) {
        _alertController.message = @"请输入手机号";
     [self presentViewController:_alertController animated:YES completion:^{
         
     }];
    } else
    {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:_textFieldPhone.text, @"phone", nil];
        [DLWNetworkingParser POSTWithURL:@"http://api.danjiguanjia.com/v1/Code/sendVerCode" par:dic success:^(id responseObject) {
            
            NSString *msg = responseObject[@"msg"];
            _alertController.message = msg;
            [self presentViewController:_alertController animated:YES completion:nil];
            if ([msg isEqualToString:@"发送成功!"])
            {
                // 倒计时
                __block int timeout= 60; //倒计时时间
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
                //每秒执行
                dispatch_source_set_event_handler(_timer, ^{
                    if(timeout<=0){ //倒计时结束，关闭
                        dispatch_source_cancel(_timer);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //设置界面的按钮显示 根据自己需求设置
                            [_buttonGetText setTitleColor:[UIColor colorWithRed:0.157 green:0.651 blue:0.278 alpha:1.000] forState:UIControlStateNormal];
                            [_buttonGetText setTitle:@"重新获取" forState:UIControlStateNormal];
                            _buttonGetText.userInteractionEnabled = YES;
                            
                        });
                    }else{
                        int seconds = timeout;
                        NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //让按钮变为不可点击的灰色
                            _buttonGetText.userInteractionEnabled = NO;
                            //设置界面的按钮显示 根据自己需求设置
                            [UIView beginAnimations:nil context:nil];
                            [UIView setAnimationDuration:1];
                            [_buttonGetText setTitle:[NSString stringWithFormat:@"%@秒后获取",strTime] forState:UIControlStateNormal];
                            [_buttonGetText setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                            [UIView commitAnimations];
                        });
                        timeout--;
                    }
                });
                dispatch_resume(_timer);
                
            }
            } filed:^(NSError *error) {
            
        }];
    }
    
}

#pragma mark -  注册
- (void)registerAction:(BaseButton *)button
{
    if (![ZhengZe isMobile:_textFieldPhone.text]) {
        _alertController.message = @"请输入正确电话号";
        [self presentViewController:_alertController animated:YES completion:nil];
    } else if ([_textfieldText.text isEqualToString:@""])
    {
        _alertController.message = @"请输入验证码";
        [self presentViewController:_alertController animated:YES completion:nil];
    } else if (_textFieldPwd.text.length < 6)
    {
        _alertController.message = @"密码位数大于6位,用字母和数字";
        [self presentViewController:_alertController animated:YES completion:nil];
    } else
    {
        NSLog(@"%@", _textfieldText.text);
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:_textFieldPhone.text, @"user_name",_textfieldText.text,@"code", _textFieldPwd.text, @"user_pwd", nil];
        [DLWNetworkingParser POSTWithURL:@"http://api.danjiguanjia.com/v1/User/register" par:dic success:^(id responseObject) {
            NSLog(@"%@", responseObject);
            NSString *msg = responseObject[@"msg"];
            _alertController.message = msg;
            [self presentViewController:_alertController animated:YES completion:nil];
        } filed:^(NSError *error) {
            
        }];
    }
}

#pragma mark -text协议,回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

// 界面随键盘上调
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView beginAnimations:@"wang" context:nil];
    [UIView setAnimationDuration:0.3];
    self.view.frame = CGRectMake(0, -100, self.view.bounds.size.width, self.view.bounds.size.height);
    [UIView commitAnimations];
    // 小条变色
    if (textField == _textFieldPhone) {
        _viewPhone.backgroundColor = [UIColor colorWithRed:0.157 green:0.651 blue:0.278 alpha:1.000];
    } else if (textField == _textFieldPwd)
    {
        _viewPwd.backgroundColor = [UIColor colorWithRed:0.157 green:0.651 blue:0.278 alpha:1.000];
    } else
    {
        _viewText.backgroundColor = [UIColor colorWithRed:0.157 green:0.651 blue:0.278 alpha:1.000];
    }

    
}
// 界面随键盘回来
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView beginAnimations:@"dao" context:nil];
    [UIView setAnimationDuration:0.3];
    self.view.frame = CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height);
    [UIView commitAnimations];
    // 小条变色
    if (textField == _textFieldPhone) {
        _viewPhone.backgroundColor = [UIColor grayColor];
    } else if (textField == _textFieldPwd)
    {
        _viewPwd.backgroundColor = [UIColor grayColor];
    } else
    {
        _viewText.backgroundColor = [UIColor grayColor];
    }
    
}

#pragma mark -添加下滑手势,回收键盘
- (void)addGesture
{
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    
    [self.view addGestureRecognizer:tapGesture];
}
-(void)tapAction:(UITapGestureRecognizer *)tap
{
    [_textFieldPwd resignFirstResponder];
    [_textFieldPhone resignFirstResponder];
    [_textfieldText resignFirstResponder];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
